﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBBSWebApi.BLL;
using MyBBSWebApi.BLL.Interfaces;
using MyBBSWebApi.DAL;
using MyBBSWebApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace jie_kou_san_ceng_jia_gou.Controllers
{
    [Route("api/[controller]/[action]")]
    /*restful路由风格:[Route("[controller]")]
     * restful风格的路由方式，是一个controller中只能包含一个HttpGet，如果要包含多个HttpGet，则需要进行路由重载
      [HttpGet("userno"/"password")]，则可以解决 */
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly IUserBll userBll;

        //构造函数，一个类必有一个构造函数，也可以有多个构造函数
        public LoginController(IUserBll userBll)
        {
            this.userBll = userBll;
        }

        //获取所有用户数据的接口
        [HttpGet]
        public List<Users> GetAll()
        {
            //不使用IUserBll接口时候的命令----两种方法都可以，使用接口的方式，可以规范类
            //UserBll userBll = new UserBll();

            //使用IUserBll接口时候的命令
            //IUserBll userBll = new UserBll();//使用依赖注入以后，可以不使用new来实例化一个对象

            List<Users> userList = userBll.GetAll();
            return userList;
        }

        //获取用户登录数据的接口
        [HttpGet]
        //public string Get(string userno, string password)  //使用前面三种未封装前的返回值类型为string

        public Users GetLogin(string userno, string password)    //使用三层架构进行封装后的返回值类型为Users对象
        {
            /*//连接redis
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,password=123456");
            IDatabase db = redis.GetDatabase();
            string value = "name";
            db.StringSet("mykey", value);
            Console.WriteLine(db.StringGet("mykey"));*/

            /*//初始①：连接sql-并返回sql中的数据-下面get行为没有封装前的代码
            SqlConnection conn = new SqlConnection("server=.;database=mybbsdb;uid=sa;pwd=123456;TrustServerCertificate=True");
            conn.Open();

            SqlCommand cmd = new SqlCommand("SELECT * FROM users", conn);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            sda.Fill(ds);
            DataTable res = ds.Tables[0];
            DataRow dr = res.Rows[0];

            conn.Close();
            conn.Dispose();

            var res_userno = dr["userno"].ToString();
            var res_password = dr["password"].ToString();
            if (res_userno == userno && res_password == password)
            {
                return "登录成功";
            }
            else
            {
                return "用户名或者密码错误";
            }*/



            /*//②get行为进行封装后的代码-通过SqlHelper.cs文件进行的封装
            //如果不使用静态类，则需要实例化对象；如果使用静态类则不需要实例化对象
            //SqlHelper sqlHelper = new SqlHelper();------用来实例化类
            //SqlHelper sqlHelper = new SqlHelper();
            DataTable res = SqlHelper.ExecuteTable("SELECT * FROM users");
            DataRow dr = null;
            if (res.Rows.Count > 0)
            {
                dr = res.Rows[0];
            }

            var res_userno = dr["userno"].ToString();
            var res_password = dr["password"].ToString();
            if (res_userno == userno && res_password == password)
            {
                return "登录成功";
            }
            else
            {
                return "用户名或者密码错误";
            }*/


            /*//对行为get进行数据访问层的封装后代码
            UserDal userdal = new UserDal();
            bool hasUser = userdal.GetUserByusernoAndpassword(userno, password);
            if (hasUser)
            {
                return "登录成功";
            }
            else
            {
                return "用户名或者密码错误";
            }*/

            //使用三层架构进行封装后的代码
            //UserBll userBll = new UserBll();//使用依赖注入以后，可以不使用new来实例化一个对象
            Users user = userBll.CheckLogin(userno, password);
            return user;
        }

        //向库中插入数据的接口
        [HttpPost]
        public string Insert(int id, string userno, string username, int userlevel, string password)
        {
            /*//连接sql并向sql中插入数据，下面为insert行为没有封装前的代码
            using SqlConnection conn = new SqlConnection("server=.;database=mybbsdb;uid=sa;pwd=123456;TrustServerCertificate=True");
            conn.Open();
            SqlCommand cmd = new SqlCommand($"INSERT INTO users(id, userno, username, userlevel, password) VALUES ({id}, '{userno}', '{username}', {userlevel}, '{password}')", conn);
            cmd.ExecuteNonQuery();

            return "插入数据成功";*/


            /*//insert行为封装后的代码
            //SqlHelper sqlHelper = new SqlHelper();
            SqlHelper.ExecuteNonQuery(
                "INSERT INTO users(id, userno, username, userlevel, password) VALUES (@id, @userno, @username, @userlevel, @password)",
                new SqlParameter("@id", id),
                new SqlParameter("@userno", userno),
                new SqlParameter("@username", username),
                new SqlParameter("@userlevel", userlevel),
                new SqlParameter("password", password));

            return "数据插入成功";*/


            /*//对行为insert数据层访问进行封装后的代码
            //下面代码应该属于业务逻辑层Bll层
            UserDal userDal = new UserDal();
            int i = userDal.AddUser(id, userno, username, userlevel, password);
            if (i > 0)
            {
                return "数据插入成功";
            }
            else
            {
                return "数据插入失败";
            }*/
            return userBll.AddUser(id, userno, username, userlevel, password);
        }

        [HttpPut]

        // int? userlevel解释:userlevel为可空整形，如果传递的参数userlevel为空，则可以不传递参数，如果传递的参数userlevel不为空，则按照传入的参数来进行传参
        public string Update(int id, string userno, string username, int? userlevel, string password)
        {
            /*//连接sql并按照需求更新对应的数据，下面为update行为封装前的代码
            SqlConnection conn = new SqlConnection("server=.;database=mybbsdb;uid=sa;pwd=123456;TrustServerCertificate=True");
            conn.Open();
            SqlCommand cmd = new SqlCommand("UPDATE users Set password = 'helloword' WHERE id = 5", conn);
            cmd.ExecuteNonQuery();

            return "数据更新成功";*/


            /*//下面为update行为封装后的代码
            //SqlHelper sqlHelper = new SqlHelper();
            DataTable res = SqlHelper.ExecuteTable("SELECT * FROM users WHERE id = @id", new SqlParameter("@id", id));
            if (res.Rows.Count > 0)
            {
                DataRow row = res.Rows[0];

                Users user = new Users();
                user.Id = (int)row["id"];
                user.Userno = userno?? row["userno"].ToString();  //有改变的值按改变后的，没有改变的值按原始值进行占位参数userno为空，则按照原来的参数传递；如果参数不为空，则按已有的参数传递
                user.Username = username?? row["username"].ToString();
                user.Userlevel = userlevel?? (int)row["userlevel"];
                user.Password = password?? row["password"].ToString();

                SqlHelper.ExecuteNonQuery(
                    "UPDATE users Set userno = @userno, username = @username, userlevel = @userlevel, password = @password WHERE id = @id",
                    new SqlParameter("@userno", user.Userno),
                    new SqlParameter("@username", user.Username),
                    new SqlParameter("@userlevel", user.Userlevel),
                    new SqlParameter("@password", user.Password),
                    new SqlParameter("@id", user.Id));
            }

            return "数据按需求更新成功";*/


            //对update行为数据访问层进行封装后的代码
            /*UserDal userDal = new UserDal();
            int i = userDal.UpdateUser(id, userno, username, userlevel, password);
            if (i > 0)
            {
                return "数据按需求更新成功";
            }
            else
            {
                return "数据按需求更新失败";
            }*/
            return userBll.UpdateUser(id, userno, username, userlevel, password);
        }

        [HttpDelete]
        public string Remove_id_userno_username(int id, string userno, string username)
        {
            /*//连接sql并按照要求删除对应的数据，下面为remove行为封装前的代码
            SqlConnection conn = new SqlConnection("server=.;database=mybbsdb;uid=sa;pwd=123456;TrustServerCertificate=True");
            conn.Open();
            //sql语句参数化，以防止出现sql注入现象
            SqlCommand cmd = new SqlCommand($"DELETE FROM users WHERE id = @id AND userno= @userno AND username=@username", conn);
            SqlParameter[] sqlParameters = new SqlParameter[]
            {
                new SqlParameter("@id", id),
                new SqlParameter("@userno", userno),
                new SqlParameter("@username", username)
            };

            cmd.Parameters.AddRange(sqlParameters);
            cmd.ExecuteNonQuery();

            return "数据删除成功";*/


            /*//下面为remove行为封装后的代码
            //SqlHelper sqlHelper = new SqlHelper();
            SqlHelper.ExecuteNonQuery(
                "DELETE FROM users WHERE id = @id AND userno= @userno AND username=@username",
                new SqlParameter("@id", id),
                new SqlParameter("@userno", userno),
                new SqlParameter("@username", username));

            return "数据删除成功";*/


            //对remove行为进行数据层访问封装后的代码
            /*UserDal userDal = new UserDal();
            int i = userDal.RemoveUser(id, userno, username);
            return $"{i}:数据删除成功";*/
            return userBll.RemoveUser(id, userno, username);
        }

        [HttpDelete]
        public string Remove_id(int id)
        {
            /*UserDal userDal = new UserDal();
            int i = userDal.RemoveID(id);
            return $"{i}:数据删除成功";*/
            return userBll.RemoveID(id);
        }
    }
}
